#include "board.h"
#include "media_service.h"

#define TAG "MEDIA_SERVICE"

struct media_service_t {
    uint8_t sys_volume;
    audio_player_config_t player_config;
};

struct media_service_t media_service;

uint8_t get_sys_volume()
{
    return media_service.sys_volume;
}

// 设置MUTE处理函数
static esp_err_t media_player_mute_fn(AUDIO_PLAYER_MUTE_SETTING setting)
{
    esp_err_t ret = ESP_OK;
    // 获取当前音量
    uint8_t volume = get_sys_volume(); 
    // 判断是否需要静音
    audio_manager_set_mute(setting == AUDIO_PLAYER_MUTE ? true : false);
    // 如果不是静音 设置音量
    if (setting == AUDIO_PLAYER_UNMUTE) {
        audio_manager_set_volume(volume, NULL);
    }
    ret = ESP_OK;

    return ret;
}

// 播放音乐函数 播放音乐的时候 会不断进入
static esp_err_t media_player_write_fn(void *audio_buffer, size_t len, size_t *bytes_written, uint32_t timeout_ms)
{
    esp_err_t ret = ESP_OK;

    ret = audio_manager_i2s_write(audio_buffer, len, bytes_written, timeout_ms);

    return ret;
}

// 设置采样率 播放的时候进入一次
static esp_err_t media_player_std_clock(uint32_t rate, uint32_t bits_cfg, i2s_slot_mode_t ch)
{
    esp_err_t ret = ESP_OK;

    ret = audio_manager_set_sampling_rate(rate, bits_cfg, ch);

    return ret;
}

int media_service_init()
{
    media_service.sys_volume = CODEC_DEFAULT_VOLUME;

    // 初始化音频播放
    media_service.player_config.mute_fn = media_player_mute_fn;
    media_service.player_config.write_fn = media_player_write_fn;
    media_service.player_config.clk_set_fn = media_player_std_clock;
    media_service.player_config.priority = MEDIA_SVC_TASK_PRIORITY;
    media_service.player_config.coreID = MEDIA_SVC_TASK_CORE;

    ESP_ERROR_CHECK(audio_player_new(media_service.player_config));

    return 0;
}
